"""
Case Type   : 事件触发器
Case Name   : 【事件触发器】使用gs_dump/gs_restore导出导入
Create At   : 2024/07/08
Owner       : sungang14
Description :
    预置条件：
        1.创建事件触发器：
       CREATE OR REPLACE FUNCTION f_eventtrigger_0002()
       RETURNS event_trigger
       LANGUAGE plpgsql
       AS $$ BEGIN
       RAISE NOTICE 'test_event_trigger: % %', tg_event, tg_tag;
       END;
       $$;
       CREATE EVENT TRIGGER start_eventtri ON ddl_command_start EXECUTE PROCEDURE f_eventtrigger_0002();
        2、创建新数据库
        create database db_eventtrigger_0002;
        3、创建用户
        create user u_eventtrigger_0002 sysadmin password 'Huawei@123';
    测试步骤：
        1.导出数据：
        gs_dump -U u_test -W Huawei@123 -f $GAUSSHOME/backup_test_db.tar -p 57442 postgres -F t
        2.导入数据到新数据库：
        gs_restore -U u_test -W Huawei@123 $GAUSSHOME/backup_test_db.tar -p 57442 -d db_eventtrigger_0002
        3.在数据库db_eventtrigger_0002中执行：
        CREATE TABLE test1(id int, col int);
Expect      :
    1.导出成功，文件包含创建事件触发器SQL
    2.导入成功
    3.触发执行函数f_eventtrigger_0002()
    test_event_trigger: ddl_command_start,CREATE TABLE
History     : 
"""

import sys
import os
import unittest
from yat.test import Node
from yat.test import macro

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH


class IndexFileDamaged(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f'-----{os.path.basename(__file__)} start-----')
        self.logger.info('----------------this is setup-----------------------')
        self.DB_ENV_PATH = macro.DB_ENV_PATH
        self.DB_INSTANCE_PATH = macro.DB_INSTANCE_PATH
        self.comsh = CommonSH('PrimaryDbUser')
        self.pri_comsh = Node('PrimaryDbUser')
        self.userNode = self.comsh.node
        self.fun_name = "f_eventtrigger_0002()"
        self.user_name = "u_eventtrigger_0002"
        self.db_name = "db_eventtrigger_0002"
        self.t_name = "t_eventtrigger_0002"
        self.comsh.execut_db_sql("drop EVENT TRIGGER if exists start_eventtri;")
        self.comsh.execut_db_sql(f"drop function if exists {self.fun_name};")
        msg = self.comsh.execut_db_sql(
            f"CREATE OR REPLACE FUNCTION {self.fun_name} RETURNS event_trigger LANGUAGE plpgsql" \
            f" AS \$\$ BEGIN" \
            f" RAISE NOTICE 'test_event_trigger: % %', tg_event, tg_tag;" \
            f"END;" \
            f"\$\$;")
        self.logger.info(msg)
        self.assertEqual("CREATE FUNCTION", msg)
        msg = self.comsh.execut_db_sql(
            f"CREATE EVENT TRIGGER start_eventtri ON ddl_command_start EXECUTE PROCEDURE {self.fun_name};")
        self.logger.info(msg)
        self.assertEqual("CREATE EVENT TRIGGER", msg)
        self.comsh.execut_db_sql(f"drop USER if exists {self.user_name};")
        msg = self.comsh.execut_db_sql(f"create user {self.user_name} sysadmin password 'Huawei@123';")
        self.logger.info(msg)
        self.assertEqual("CREATE ROLE", msg)
        self.comsh.execut_db_sql(f"drop database if exists {self.db_name};")
        msg = self.comsh.execut_db_sql(f"create database {self.db_name};")
        self.logger.info(msg)
        self.assertEqual("CREATE DATABASE", msg)

    def test_Index_file_damaged(self):
        self.logger.info(
            '从当前数据库导出数据,f"gs_dump -U {self.user_name} -W Huawei@123 -f $GAUSSHOME/backup_test_db.tar -p {self.userNode.db_port} {self.userNode.db_name} -F t"')
        msg = self.comsh.exec_gs_dump(filename=f" $GAUSSHOME/backup_test_db.tar -U {self.user_name} -W Huawei@123 ",
                                      dbname=f"{self.userNode.db_name}")
        self.logger.info(msg)
        self.assertIn(f"dump database {self.userNode.db_name} successfully", msg)

        self.logger.info(
            '导入数据到新数据库，f"gs_restore -U {self.user_name} -W Huawei@123 -f $GAUSSHOME/backup_test_db.tar -p {self.userNode.db_port} -d {self.db_name}"')
        msg = self.comsh.exec_gs_restore(username=self.user_name, user_password="Huawei@123",
                                         filename="$GAUSSHOME/backup_test_db.tar", dbname=self.db_name)
        self.logger.info(msg)
        self.assertIn(f"restore operation successful", msg)

        self.logger.info(f"在数据库db_eventtrigger_0002中执行：CREATE TABLE test1(id int, col int);")
        msg = self.comsh.execut_db_sql(f"create table {self.t_name}(id int, col int);", dbname=self.db_name)
        self.logger.info(msg)
        self.assertIn("CREATE TABLE", msg)
        self.assertIn(f"test_event_trigger: ddl_command_start CREATE TABLE", msg)

    def tearDown(self):
        self.logger.info('----------------this is tearDown-----------------------')
        # 删除事件触发器
        msg = self.comsh.execut_db_sql("drop EVENT TRIGGER if exists start_eventtri;")
        self.logger.info(msg)
        self.assertEqual('DROP EVENT TRIGGER', msg)
        # 删除事件触发器函数
        msg = self.comsh.execut_db_sql("drop function if exists f_eventtrigger_0002();")
        self.logger.info(msg)
        self.assertEqual('DROP FUNCTION', msg)
        # 删除数据库
        msg = self.comsh.execut_db_sql(f"drop database if exists {self.db_name};")
        self.logger.info(msg)
        self.assertIn('DROP DATABASE', msg)
        # 删除用户
        msg = self.comsh.execut_db_sql(f"drop USER if exists {self.user_name};")
        self.logger.info(msg)
        self.assertIn('DROP ROLE', msg)
        self.logger.info(f'-----{os.path.basename(__file__)} end-----')
        # # 删除导出文件
        msg = self.pri_comsh.sh("rm -rf $GAUSSHOME/backup_test_db.tar").result()
        self.logger.info(msg)
